package com.numberone.master.common.exception;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.engine.impl.util.json.JSONObject;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;


/**
 * 统一异常处理
 * 
 * @author ck
 *
 * @date 2017年8月22日上午9:54:37
 */
public class GlobalExceptionResolver extends SimpleMappingExceptionResolver {
	@Override
	protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		String viewName = determineViewName(ex, request);
		response.setCharacterEncoding("UTF-8");
		if (viewName != null) {
			// JSP格式返回
			if (!(request.getHeader("accept").contains("application/json")
					|| (request.getHeader("X-Requested-With") != null
							&& request.getHeader("X-Requested-With").contains("XMLHttpRequest")))) {
				// 如果不是异步请求
				Integer statusCode = determineStatusCode(request, viewName);
				if (statusCode != null) {
					applyStatusCodeIfPossible(request, response, statusCode);
					return getModelAndView(viewName, ex, request);
				}else{
					// JSON格式返回
					try {
						PrintWriter writer = response.getWriter();
						JSONObject obj = new JSONObject();
						obj.put("code", "502");
						obj.put("msg", "系统错误");
						if (viewName.equals("/common/notPermission")) {
							obj.put("code", "507");
							obj.put("msg", "您没有操作的权限");
						} else {
							// 向下强转
							BizException r1 = new BizException();
							if (ex instanceof BizException) {
								r1 = (BizException) ex;
								obj.put("code", r1.getErrorCode());
								obj.put("msg", r1.getMessage());
							}
						}
						writer.write(obj.toString());
						writer.flush();
						writer.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
					return null;
				}
			} else {
				// JSON格式返回
				try {
					PrintWriter writer = response.getWriter();
					JSONObject obj = new JSONObject();
					obj.put("code", "502");
					obj.put("msg", "系统错误");
					if (viewName.equals("/common/notPermission")) {
						obj.put("code", "507");
						obj.put("msg", "您没有操作的权限");
					} else {
						// 向下强转
						BizException r1 = new BizException();
						if (ex instanceof BizException) {
							r1 = (BizException) ex;
							obj.put("code", r1.getErrorCode());
							obj.put("msg", r1.getMessage());
						}
					}
					writer.write(obj.toString());
					writer.flush();
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				return null;
			}
		} else {
			return null;
		}
	}
}
